<template>
  <div>
    <el-dialog :title="title" center  :visible="open" :modal="open" @close="close()" width="70%" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="92px">
        <el-form-item :label="$t('authority.dictInfo.form.dictName')" prop="dictName">
          <el-input v-model="form.dictName" :placeholder="$t('authority.dictInfo.rules.dictNamePLH')" />
        </el-form-item>
        <el-form-item :label="$t('authority.dictInfo.form.dictType')" prop="dictType">
          <el-input v-model="form.dictType" :placeholder="$t('authority.dictInfo.rules.dictTypePLH')" />
        </el-form-item>
        <el-form-item :label="$t('authority.dictInfo.form.status')" prop="status">
          <el-select
            v-model="form.status"
            :placeholder="$t('authority.dictInfo.form.status')"
            clearable
            class="common-select"
            @change="selChange"
          >
<!--            <el-option key="0" value="0" :label="$t('authority.dictInfo.rules.selectTip')"></el-option>-->
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.text" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('authority.dictInfo.form.remark')" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :placeholder="$t('authority.dictInfo.rules.contentPLH')"
            maxlength="256"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddChild"
          v-hasPermi="['user:dictInfo:add']"
        >
          {{ $t("common.add") }}
        </el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteChild"
          v-hasPermi="['user:dictInfo:removeAll']"
        >
          {{ $t("common.delete") }}
        </el-button>
      </el-row>
      <el-table :data="typeDataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column :label="$t('authority.dictInfo.form.dictLabel')" align="left" prop="dictLabel" />
        <el-table-column :label="$t('authority.dictInfo.form.dictNumber')" align="left" prop="dictCode" />
        <el-table-column :label="$t('authority.dictInfo.form.dictOption')" align="center" prop="dictValue" />
        <el-table-column :label="$t('authority.dictInfo.form.dictOptionSort')" align="center" prop="dictSort" />
        <!-- <el-table-column label="列表样式" align="center" prop="cssClass" /> -->
        <el-table-column
          :label="$t('authority.dictInfo.form.remark')"
          align="left"
          prop="remark"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ !scope.row.remark ? "-" : scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.operate')" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdateChild(scope.row)"
              v-hasPermi="['user:dictInfo:edit']"
            >
              {{ $t("common.modifyBtn") }}
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteChild(scope.row)"
              v-hasPermi="['user:dictInfo:remove']"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t("common.confirm") }}</el-button>
        <el-button @click="close">{{ $t("common.cancel") }}</el-button>
      </div>
    </el-dialog>

    <data-info
      v-if="openData"
      :dataId="curDataId"
      :title="dataTitle"
      :open="openData"
      @changeDataInfoOpen="changeDataInfoOpen"
    ></data-info>
  </div>
</template>

<script>
import DataInfo from "./dataInfo";
import { getType, preAddOrUpdate, addOrUpdateType, checkDictType } from "@/api/authority_app/dict/type";
import { delData, getData, saveOrUpdateData, searchDictData } from "@/api/authority_app/dict/data";
export default {
  name: "TypeInfo",
  components: {
    DataInfo,
  },
  data() {
    // 表单校验
    var checkDictTypeUnique = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error(this.$t("authority.dictInfo.rules.dictTypeNoEmpty")));
      } else {
        checkDictType({
          id: this.form.id,
          dictType: this.form.dictType,
        }).then((response) => {
          var result = response.result;
          if (!result) {
            callback(new Error(this.$t("authority.dictInfo.rules.dictTypeExists")));
          } else {
            callback();
          }
        });
      }
    };
    return {
      form: {
        dictName: "",
        dictType: "",
        status: "",
        remark: "",
      },
      // 表单校验
      rules: {
        dictName: [
          {
            required: true,
            message: this.$t("authority.dictInfo.rules.dictNameNoEmpty"),
            trigger: "blur",
          },
          {
            max: 30,
            message: '字典名称最长30位',
            trigger: "blur",
          },
        ],
        dictType: [{ required: true, validator: checkDictTypeUnique, trigger: "blur" }, {
          max: 30,
          message: '字典类型最长30位',
          trigger: "blur",
        },],
        status: [
          {
            required: true,
            message: this.$t("authority.dictInfo.rules.stateSelectTip"),
            trigger: "change",
          },
        ],
      },
      // 选中数组
      ids: [],
      single: true,
      // 非多个禁用
      multiple: true,
      statusOptions: [],
      typeDataList: [],
      //子弹窗使用
      openData: false,
      curDataId: "",
      dataTitle: "",
    };
  },
  props: {
    typeId: {
      type: String,
      default: "",
    },
    title: {
      type: String,
      default: "",
    },
    open: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.result;
    });
    //重置表单
    this.reset();
    this.typeDataList = [];

    //执行预新增或者预修改
    this.doPreAddOrUpdate().then((res) => {
      if (this.typeId && this.typeId != "") {
        getType(this.typeId).then((response) => {
          this.form = response.result;
          this.form.status += "";
          this.open = true;
          // this.title = "修改字典类型";
          this.loadDataByDict();
        });
      }
    });
  },
  methods: {
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      console.log("ids:", this.ids);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    //加载字典类型下的数据
    loadDataByDict() {
      searchDictData().then((res) => {
        this.typeDataList = res.result.data;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: "",
        dictName: "",
        dictType: "",
        status: "",
        remark: "",
      };
      this.resetForm("form");
    },
    doPreAddOrUpdate() {
      return preAddOrUpdate();
    },
    selChange(e) {
      this.form.status = e;
    },
    handleAddChild() {
      this.openData = true;
      this.dataTitle = this.$t("authority.dictInfo.form.addDictData");
    },
    /** 修改按钮操作 */
    handleUpdateChild(row) {
      this.curDataId = row.id || this.ids[0];
      this.openData = true;
      this.dataTitle = this.$t("authority.dictInfo.form.updateDictData");
    },
    // 取消按钮
    close() {
      this.reset();
      this.$emit("changeTypeInfoOpen", false);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          delete this.form.dataList;
          delete this.form.createTime;
          delete this.form.updateTime;
          addOrUpdateType(this.form).then((res) => {
            this.msgSuccess(this.$t("common.operateSuccess"));
            this.close();
          });
        }
      });
    },
    handleDeleteChild(row) {
      const dictIds = row.id || this.ids;
      let confirmText = "";
      if (this.ids.length == 0) {
        confirmText = this.$t("authority.dictInfo.rules.deleteTips");
      } else {
        confirmText = this.$t("authority.dictInfo.rules.multiDeleteTip", {
          val: this.ids.length,
        });
      }
      this.$confirm(confirmText, this.$t("authority.dictInfo.form.warning"), {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(function () {
          return delData(dictIds);
        })
        .then(() => {
          this.loadDataByDict();
          this.msgSuccess(this.$t("common.deleteSuccess"));
        })
        .catch((action) => {});
    },
    changeDataInfoOpen(open) {
      this.openData = open;
      this.curDataId = "";
      if (!this.openData) {
        this.loadDataByDict();
      }
    },
  },
};
</script>
